package keter.security;

import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;

import keter.model.Role;
import keter.model.User;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


/**
 * Adapts User model from pl.edu.agh.mea.domain package to make it usable in
 * Spring Security authentication mechanism.
 * 将应用的User转换为Spring的User
 * @author Dawid Fatyga
 * 
 */
public class UserAdapter implements UserDetails {
	private static final long serialVersionUID = 1L;

	transient private User user;
	
	public UserAdapter() {
	}

	public UserAdapter(User user) {
		this.user = user;
	}
	
	/**
	 * @param force
	 *            allows to fetch user from database (not from cache)
	 * @return user instance
	 */
	public User getUser() {
		return user;
	}

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
	    Set<GrantedAuthority> grantedAuthorities = new TreeSet<GrantedAuthority>();
	    user.getRoleList().forEach(role->{
            grantedAuthorities.add(new AuthorityAdapter(role));
	    });
//        for (Role role : user.getRoleList()) {
//            grantedAuthorities.add(new AuthorityAdapter(role));
//        }
        return grantedAuthorities;
	}

	@Override
	public String getPassword() {
		return user.get("password");
	}

	@Override
	public String getUsername() {
		return user.get("username");//系统采用“账号”作为登录验证
	}

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}